package com.sky.service.impl;


import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    OrderMapper orderMapper;


    @Autowired
    UserMapper userMapper;

    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
//        1.组装x轴数据集合   ---- ["2023-04-27","2023-04-28"]

        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

//       1.1 依次添加日期进集合，每次+1天，直到end
        while (!begin.equals(end)){
            log.info("日期；"+begin);
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
//["2023-04-27","2023-04-28","2023-04-29",...,,"2023-05-03"]
        ArrayList<Double> turnoverList = new ArrayList<>();
//        2.遍历x轴数据，组装y轴数据集合
        for (LocalDate localDate : dateList) {
//            1.状态：已完成的订单
//            2.时间：一天的开始和一天的结束时间
//            localDate==2023-04-27
            LocalDateTime min = LocalDateTime.of(localDate, LocalTime.MIN); //2023-04-27 00:00:00
            LocalDateTime max = LocalDateTime.of(localDate, LocalTime.MAX);


            HashMap<Object, Object> map = new HashMap<>();
            map.put("status",Orders.COMPLETED);
            map.put("start",min);
            map.put("end",max);


            Double  turnover= orderMapper.getTurnoverByCondition(map);
//有可能营业额是null
            turnover= turnover==null?0.0:turnover;
            turnoverList.add(turnover);

        }


//        3.将x、y轴数据按照接口文档格式要求，封装成一个VO对象返回
        TurnoverReportVO reportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();

        return reportVO;
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {

        //        1.组装x轴数据集合   ---- ["2023-04-27","2023-04-28"]

        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
//       1.1 依次添加日期进集合，每次+1天，直到end
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

//       2.组装Y轴的所有用户的数据
        ArrayList<Integer> totalUserCount = new ArrayList<>();
//        2.1 组装Y轴的新增用户的数据
        ArrayList<Integer> newUserCount = new ArrayList<>();

        for (LocalDate localDate : dateList) {

            LocalDateTime startTime= LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime= LocalDateTime.of(localDate, LocalTime.MAX);


//            获得当天的总员工数
            Integer totaluc= getCountByTime(null,endTime);



//            获得当天新增员工数
            Integer newuc= getCountByTime(startTime,endTime);

            totalUserCount.add(totaluc);
            newUserCount.add(newuc);


        }





//        封装上面的数据，返回前端
        UserReportVO reportVO = UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserCount,","))
                .totalUserList(StringUtils.join(totalUserCount,","))
                .build();


        return reportVO;
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {

        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
//       1.1 依次添加日期进集合，每次+1天，直到end
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

//       2.组装Y轴的每日的总订单数据
        ArrayList<Integer> orderCountList = new ArrayList<>();
//        2.1 组装Y轴的有效订单的数据
        ArrayList<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate localDate : dateList) {

            LocalDateTime startTime= LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime= LocalDateTime.of(localDate, LocalTime.MAX);


//            获得当天的总订单数
            Integer totalOrderc= getOrderCountByTime(startTime,endTime,null);

//            获得当天有效订单数
            Integer newOrderc= getOrderCountByTime(startTime,endTime,Orders.COMPLETED);

//            totalOrderc==null


            orderCountList.add(totalOrderc);
            validOrderCountList.add(newOrderc);


        }
//        1,3,4,5,6
        Integer totalOrderCount=orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount=validOrderCountList.stream().reduce(Integer::sum).get();
//
//        for (Integer integer : orderCountList) {
//            totalOrderCount+=integer;
//        }
//        for (Integer integer : validOrderCountList) {
//            validOrderCount+=integer;
//        }
        Double orderCompletionRate=0.0;
//        为了避免除零异常
        if (totalOrderCount!=0){
             orderCompletionRate =validOrderCount.doubleValue()/totalOrderCount.doubleValue();
        }


        OrderReportVO reportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate).build();
        return reportVO;
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {

//        1.求出数据集合
        LocalDateTime startTime= LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime= LocalDateTime.of(end, LocalTime.MAX);


        HashMap<Object, Object> map = new HashMap<>();
        map.put("start",startTime);
        map.put("end",endTime);

       List<OrderDetail> details= orderMapper.top10(map);

        log.info("订单数据：{}", Arrays.toString(details.toArray()));
//        [OrderDetail( name=草鱼2斤, number=5), OrderDetail(name=江团鱼2斤 , number=2)]

        List<String> nameList = details.stream().map(s -> s.getName()).collect(Collectors.toList());
        List<String> numberList = details.stream().map(s -> s.getNumber()+"").collect(Collectors.toList());

        String nameListstr=StringUtils.join(nameList,",");
        String numberListstr=StringUtils.join(numberList,",");

//        nameList：草鱼2斤,江团鱼2斤
//       numberList：5,2
        SalesTop10ReportVO vo = SalesTop10ReportVO.builder().nameList(nameListstr).numberList(numberListstr).build();

        return vo;
    }

    /**
     * 查询当天的订单数量（总的和有效的）
     * @param startTime
     * @param endTime
     * @param o
     * @return
     */
    private Integer getOrderCountByTime(LocalDateTime startTime, LocalDateTime endTime, Integer status) {
        HashMap<Object, Object> map = new HashMap<>();

        map.put("start",startTime);
        map.put("end",endTime);
        map.put("status",status);

        Integer integer = orderMapper.countByMap(map);
        return integer;
    }

    /**
     * 根据时间查询用户数量
     * @param startTime
     * @param endTime
     * @return
     */
    private Integer getCountByTime(LocalDateTime startTime, LocalDateTime endTime) {
        HashMap<Object, Object> map = new HashMap<>();

        map.put("start",startTime);
        map.put("end",endTime);

        return  userMapper.countByMap(map);
    }
}
